<template>
  <view class="play-voice-container" @click.stop="playBgm" :style="'height:'+ height">
    <view class="play-voice" :style="'height:'+ height">
      <image src="../../static/shiting.png" mode="widthFix" v-if="!isPlaying"></image>
      <image src="../../static/zanting.png" mode="widthFix" v-else></image>
    </view>
  </view>
</template>

<script>
  const innerAudioContext = uni.createInnerAudioContext();
  export default {
    name: "voice-play",
    data() {
      return {
        isPlaying: false,
        isInit: false
      };
    },
    props: {
      vocieSrc: {
        type: String,
        require: true
      },
      height: {
        type: String,
        default: '75rpx'
      }
    },
    methods: {
      initListener() {
        innerAudioContext.onEnded(() => {
          console.log('play end')
          this.isPlaying = false
        })

        innerAudioContext.onStop(() => {
          console.log('play end')
          this.isPlaying = false
        })
        innerAudioContext.onError(res => {
          console.log(res)
          this.isPlaying = false;
        })
        innerAudioContext.onCanplay(() => {
          innerAudioContext.play()
        })
      },
      playBgm() {
        if (!this.isPlaying) {
          innerAudioContext.src = this.vocieSrc;
          if (!this.isInit) {
            this.initListener()
            this.isInit = true
          }
          this.isPlaying = true;

        } else {
          this.isPlaying = false;
          innerAudioContext.pause()
        }
      },
    }
  }
</script>

<style lang="scss">
  .play-voice-container {
    margin: 0 auto;
    height: 75rpx;
    width: 400rpx;
    position: relative;
    border-radius: 75rpx;
    border: 1px solid #4bc7bd;
    background: url('');
    background-size: contain;
    background-position: 0 50%;
    background-repeat: no-repeat;
  }

  .play-voice {
    width: 110rpx;
    height: 75rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #6bd6cc;
    border-radius: 75rpx;
    float: right;

    image {
      width: 50rpx;
      height: 50rpx;
    }
  }
</style>